// Copyright  2012 Petr TALLA. [petr.talla@gmail.com]
//
// This file is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation; either
// version 2 of the License, or (at your option) any later version.
//
// This file is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY;  without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU Lesser General Public License for more details.
// [http://www.gnu.org/copyleft/lesser.html]
//=============================================================================
#include "./TcXdb.h"
#include "./TcXdbIterator.h"
#include "./TcXobject.h"
#include "./TcXattrSTR.h"
#include <assert.h>

using namespace std;

TcXdb* TcXdb::active_ = NULL;

//=============================================================================
TcXdb::TcXdb(const char* name) :
    name_(name)
{   active_ = this;
}

//=============================================================================
void TcXdb::append(TcXobject* xobj)
{   items_.push_back(xobj);

    assert(xobj->db_ == NULL);
    xobj->db_ = this;
}

//=============================================================================
TcXdbIterator* TcXdb::iterator()
{   return new TcXdbIterator(this);
}

//=============================================================================
void TcXdb::toCmds( string& r)
{
    r.append("xdb_create -name ").append(name()).append("\n");

    for ( TcXdbIterator* it = iterator(); it->NEOF(); it->next() )
    {   TcXobject* obji = it->get();

        r.append("xobject_create null");

        for ( long i = 0; i < obji->attrCount(); i++ )
        {   TcXattr* attr = obji->attrGet(i);
            TcXattrSTR* attrSTR = attr->getAsSTR();
            if ( attrSTR == NULL ) continue;

            bool spaces = true;
            string value(attrSTR->value());
            if ( value.find(' ') == string::npos ) spaces = false;

            r.append(" ");
            if (attrSTR->name()[0] != 0)
            {   r.append("-");
                r.append(attrSTR->name()).append(" ");
            }
            if (spaces) r.append("\"");
            r.append(attrSTR->value());
            if (spaces) r.append("\"");
        }

        r.append("\n");

    }
}

//=============================================================================
